<template>
  <basic-dialog :visible="show"
                title="配置"
                :isShowClose="true"
                :isShowBasicFooter="true"
                min-width="480px"
                @close="show = false"
                :loading="submitting"
                @submit="submit"
  >
    <div class="margin-b-20 margin-b-20">
      <div class="flex justify-between padding-10">
        <div>应用: {{applicationName}}</div>
        <div>版本号: {{version}}</div>
        <a :disabled="!fileUrl" @click="download">下载帮助文档</a>
      </div>
      <VueJsonEditor v-model="jsonData" :modes="['text', 'code']" mode="text"
                     @json-change="onJsonChange"
                     @has-error="onError"/>
    </div>
  </basic-dialog>
</template>

<script>
import { Base64Decoder } from '../../../../../assets/js/util'
import VueJsonEditor from 'vue-json-editor'
import { getAppFileUrl } from '../../../../../boot/miot/plc-list'

const base64Decoder = new Base64Decoder()
export default {
  name: 'config-edit-dialog',
  components: {
    VueJsonEditor
  },
  props: {
    submitting: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      mode: 'text',
      show: false,
      hasJsonFlag: true, // json是否验证通过
      jsonData: {},
      applicationName: '',
      version: '',
      appId: '',
      fileUrl: ''
    }
  },
  watch: {
    appId (val) {
      if (val) {
        getAppFileUrl(val).then(res => {
          this.fileUrl = res.data
        })
      } else {
        this.fileUrl = ''
      }
    }
  },
  methods: {
    showDialog (data) {
      this.fileUrl = ''
      this.show = true
      const config = data.config
      this.version = data.version
      this.applicationName = data.applicationName
      this.appId = data.appId
      try {
        this.jsonData = JSON.parse(base64Decoder.decode(config))
        getAppFileUrl(this.appId).then(res => {
          this.fileUrl = res.data
        })
      } catch (e) {

      }
    },
    hideDialog () {
      this.show = false
    },
    submit () {
      if (this.hasJsonFlag) {
        this.$emit('submit', JSON.stringify(this.jsonData))
      } else {
        this.$message.warning('请输入正确json文件')
      }
    },
    onJsonChange (value) {
      this.hasJsonFlag = true
      this.jsonData = value
    },
    onError (value) {
      this.hasJsonFlag = false
    },
    download () {
      const fileSplit = this.fileUrl.split('/')
      const fileName = fileSplit[fileSplit.length - 1]
      this.$saveFileForBlob(this.fileUrl, fileName)
      this.$message.success('文件下载成功！')
    }
  }
}
</script>

<style lang="scss">
.jsoneditor-menu{
  background-color:  #5f77fd!important
}
div.jsoneditor-outer{
  height: 500px;
}
</style>
